package org.jeecg.modules.demo.safemanage.zyhazardinvestigation.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.correctionType.service.IZyCorrectionTypeService;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyHazardInvestigation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyRectificationInformation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyReviewInformation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.mapper.ZyHazardInvestigationMapper;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.IZyHazardInvestigationService;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.IZyRectificationInformationService;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.IZyReviewInformationService;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.vo.QualityTypeVo;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.vo.ZyHazardInvestigationFinishStatusVo;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.vo.ZyHazardInvestigationPage;
import org.jeecg.modules.demo.zyHazardInvestigationFather.entity.ZyHazardInvestigationFather;
import org.jeecg.modules.demo.zyHazardInvestigationFather.service.IZyHazardInvestigationFatherService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: 整改监督信息
 * @Author: jeecg-boot
 * @Date: 2024-03-20
 * @Version: V1.0
 */
@Tag(name = "整改监督信息")
@RestController
@RequestMapping("/zyhazardinvestigation/zyHazardInvestigation")
@Slf4j
public class ZyHazardInvestigationController {
    @Autowired
    private IZyHazardInvestigationService zyHazardInvestigationService;
    @Autowired
    private IZyRectificationInformationService zyRectificationInformationService;
    @Autowired
    private IZyReviewInformationService zyReviewInformationService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ZyHazardInvestigationMapper zyHazardInvestigationMapper;

    @Autowired
    private IZyHazardInvestigationFatherService zyHazardInvestigationFatherService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IZyCorrectionTypeService zyCorrectionTypeService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;


    /**
     * 分页列表查询
     *
     * @param zyHazardInvestigation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "整改监督信息-分页列表查询")
    @Operation(summary = "整改监督信息-分页列表查询", description = "整改监督信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ZyHazardInvestigation>> queryPageList(ZyHazardInvestigation zyHazardInvestigation,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        QueryWrapper<ZyHazardInvestigation> queryWrapper = QueryGenerator.initQueryWrapper(zyHazardInvestigation, req.getParameterMap());
        Page<ZyHazardInvestigation> page = new Page<ZyHazardInvestigation>(pageNo, pageSize);
        IPage<ZyHazardInvestigation> pageList = zyHazardInvestigationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    public String getSessionId(HttpServletRequest request) {
        // 获取HttpSession对象
        HttpSession session = request.getSession();
        // 获取sessionId
        String sessionId = session.getId();
        return sessionId;
    }

    /**
     * 根据用户查询隐患信息
     *
     * @param zyHazardInvestigation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "整改监督信息-分页列表查询")
    @Operation(summary = "整改监督信息-根据用户查询隐患信息", description = "整改监督信息-根据用户查询隐患信息")
    @GetMapping(value = "/listByUser")
    public Result<List<ZyHazardInvestigation>> listByUser(ZyHazardInvestigation zyHazardInvestigation,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        System.out.println("loginUser.getUsername() = " + loginUser.getUsername());
        String pid = req.getParameter("pid");
        String departIds = loginUser.getDepartIds();
        String departName = sysDepartService.getDepartNameById(departIds);
        LambdaQueryWrapper<ZyHazardInvestigation> queryWrapper = new LambdaQueryWrapper<>();
        if (loginUser.getRoleCode().equals("admin")||loginUser.getRoleCode().equals("leader")){
            queryWrapper.eq(ZyHazardInvestigation::getPid, pid);
        }else if (loginUser.getRoleCode().equals("department_management")){
            queryWrapper.eq(ZyHazardInvestigation::getPid, pid)
                    .eq(ZyHazardInvestigation::getDepartment, departName);
        }
        else {
            queryWrapper.eq(ZyHazardInvestigation::getPid, pid)
                    .eq(ZyHazardInvestigation::getRectifierPerson, loginUser.getRealname());
        }
        queryWrapper.orderByDesc(ZyHazardInvestigation::getCreateTime);
        List<ZyHazardInvestigation> list = zyHazardInvestigationService.list(queryWrapper);
        return Result.OK(list);
    }





    /**
     * 统计检查结果人数
     *
     * @return
     */
    @AutoLog(value = "统计检查结果人数")
    @Operation(summary = "统计检查结果人数", description = "统计检查结果人数")
    @GetMapping(value = "/selectResult")
    public Result<Map<String, Integer>> selectResult(String pid) {
        Map<String, Integer> map = new HashMap<>();
        int rectified = 0;//待整改
        int review = 0;//待复查
        int qualified = 0;//合格
        int unqualified = 0;//不合格
        LambdaQueryWrapper<ZyHazardInvestigation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZyHazardInvestigation::getPid, pid);
        List<ZyHazardInvestigation> list = zyHazardInvestigationService.list(wrapper);
        for (ZyHazardInvestigation zyHazardInvestigation : list) {
//			 System.out.println("zyHazardInvestigation = " + zyHazardInvestigation);
            String result = zyHazardInvestigation.getResult();
//            System.out.println("result = " + result);
            Date deadline = zyHazardInvestigation.getRectificationDeadline();
//            System.out.println("deadline = " + deadline);
            if ("待整改".equals(result)) {
                rectified++;
            } else if ("待复查".equals(result)) {
                review++;
            } else if ("合格".equals(result)) {
                qualified++;
            } else if ("不合格".equals(result)) {
                unqualified++;
            }
        }
        map.put("待整改", rectified);
        map.put("待复查", review);
        map.put("合格", qualified);
        map.put("不合格", unqualified);
        return Result.OK(map);
    }


    /**
     * 统计检查结果人数
     *
     * @return
     */
    @AutoLog(value = "统计检查结果人数")
    @Operation(summary = "统计检查结果人数", description = "统计检查结果人数")
    @GetMapping(value = "/selectAllResult")
    public Result<Map<String, Integer>> selectAllResult() {
        Map<String, Integer> resultMap = new HashMap<>();

        // 获取所有重点领域
//        List<ZyCorrectionType> zyCorrectionTypes = zyCorrectionTypeService.list();
//        if (zyCorrectionTypes != null && !zyCorrectionTypes.isEmpty()) {
//            for (ZyCorrectionType CorrectionType : zyCorrectionTypes) {
//                // 获取重点领域名称
//                String questionType = CorrectionType.getCorrectionType();
//                // 统计该重点领域对应的数量
//                int count = zyHazardInvestigationService.countByFocusQualityType(questionType);
//                resultMap.put(questionType, count);
//            }
//        }

        List<DictModel> qualityType = sysBaseAPI.queryDictItemsByCode("quality_type");
        if (qualityType != null && !qualityType.isEmpty()) {
            for (DictModel CorrectionType : qualityType) {
                // 获取重点领域名称
                String questionType = CorrectionType.getText();
                // 统计该重点领域对应的数量
                int count = zyHazardInvestigationService.countByFocusQualityType(questionType);
                resultMap.put(questionType, count);
            }
        }

        return Result.OK(resultMap);
       }


    @AutoLog(value = "根据时间统计检查结果人数")
    @Operation(summary = "根据时间统计检查结果人数", description = "根据时间统计检查结果人数")
    @PostMapping(value = "/selectResultByTime")
    public Result<Map<String, Integer>> selectResultByTime(@RequestBody JSONObject object, HttpServletRequest req) {
        String start=object.getString("start");
        String end=object.getString("end");
        LocalDate startdate =LocalDate.parse(start);
        LocalDate enddate =LocalDate.parse(end);
        Map<String, Integer> map = new HashMap<>();
        int pass = 0;// 超期
        int rectified = 0;//待整改
        int review = 0;//待复查
        int qualified = 0;//合格
        int unqualified = 0;//不合格
        LambdaQueryWrapper<ZyHazardInvestigation> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(ZyHazardInvestigation::getCreateTime,startdate,enddate);
        List<ZyHazardInvestigation> list = zyHazardInvestigationService.list(wrapper);
        for (ZyHazardInvestigation zyHazardInvestigation : list) {
//			 System.out.println("zyHazardInvestigation = " + zyHazardInvestigation);
            String result = zyHazardInvestigation.getResult();
//            System.out.println("result = " + result);
            Date deadline = zyHazardInvestigation.getRectificationDeadline();
//            System.out.println("deadline = " + deadline);
            if ("待整改".equals(result)) {
                rectified++;
                if (deadline.getTime() < System.currentTimeMillis()) {
                    pass++;
                    rectified--;
                }
            } else if ("待复查".equals(result)) {
                review++;
                if (deadline.getTime() < System.currentTimeMillis()) {
                    pass++;
                    review--;
                }
            } else if ("合格".equals(result)) {
                qualified++;
            } else if ("不合格".equals(result)) {
                unqualified++;
            }
        }
        map.put("pass", pass);
        map.put("rectified", rectified);
        map.put("review", review);
        map.put("qualified", qualified);
        map.put("unqualified", unqualified);
        return Result.OK(map);
    }


    /**
     * 安全问题类型
     *
     * @param
     * @return
     */
//@AutoLog(value = "安全问题类型")
    @Operation(summary = "问题类型", description = "问题类型")
    @GetMapping(value = "/getProblemType")
    public Result<Map> getSafeType() {
        List<DictModel> dictItemsByCode = sysDictService.queryDictItemsByCode("quality_type");
        System.out.println("dictItemsByCode = " + dictItemsByCode);
        //将list转为map，方便根据键名获取对应的值
        Map<String,String> dictItemsByCodeMap = dictItemsByCode.stream().collect(Collectors.toMap(DictModel::getValue, DictModel::getText));
        return  Result.OK(dictItemsByCodeMap);
    }


    /**
     * 添加
     *
     * @param zyHazardInvestigationPage
     * @return
     */
    @AutoLog(value = "整改监督信息-添加")
    @Operation(summary = "整改监督信息-添加", description = "整改监督信息-添加")
    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ZyHazardInvestigationPage zyHazardInvestigationPage) throws ParseException {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("loginUser = " + loginUser);
        String realname = loginUser.getRealname();
        List<SysDepart> department = sysDepartService.queryDepartsByRealname(zyHazardInvestigationPage.getRectifierPerson());

        ZyHazardInvestigation zyHazardInvestigation = new ZyHazardInvestigation();
        zyHazardInvestigationPage.setDepartment(department.get(0).getDepartName());
        zyHazardInvestigationPage.setFlag(zyHazardInvestigationPage.getFlag());
        zyHazardInvestigationPage.setFile(zyHazardInvestigationPage.getFile());
        zyHazardInvestigationPage.setFileName(zyHazardInvestigationPage.getFileName());
        zyHazardInvestigationPage.setInspectionPersonnel(realname);
        zyHazardInvestigationPage.setRectifierStatus("整改中");
        zyHazardInvestigationPage.setReviewerStatus("未复查");
        zyHazardInvestigationPage.setResult("待整改");

        BeanUtils.copyProperties(zyHazardInvestigationPage, zyHazardInvestigation);
        zyHazardInvestigationService.saveMain(zyHazardInvestigation, zyHazardInvestigationPage.getZyRectificationInformationList(), zyHazardInvestigationPage.getZyReviewInformationList());
        return Result.OK("添加成功！");
    }


    /**
     * 编辑
     *
     * @return
     */
    @AutoLog(value = "流程信息添加到整改监督表中编辑")
    @Operation(summary = "流程信息添加到整改监督表中编辑", description = "流程信息添加到整改监督表中编辑")
    @RequestMapping(value = "/editWflow", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editWflow(@RequestBody JSONObject jsObject) {
        String instanceId = jsObject.getString("instanceId");
        String text= jsObject.getString("text");
        String commonProblem = jsObject.getString("commonProblem");
        String problemDescription = jsObject.getString("problemDescription");
        String measure = jsObject.getString("measure");
        LambdaUpdateWrapper<ZyHazardInvestigation> lambdaWrapper = new LambdaUpdateWrapper<>();
        lambdaWrapper.eq(ZyHazardInvestigation::getInstanceId, instanceId)
                .set(ZyHazardInvestigation::getProgress,text)
                .set(ZyHazardInvestigation::getCommonProblem,commonProblem)
                .set(ZyHazardInvestigation::getProblemDescription,problemDescription)
                .set(ZyHazardInvestigation::getMeasure,measure);
        zyHazardInvestigationService.update(lambdaWrapper);
        return Result.OK("编辑成功!");
    }


//    /**
//     * 添加
//     *
//     * @param zyHazardInvestigation
//     * @return
//     */
//    @AutoLog(value = "整改监督信息-添加")
//    @Operation(summary = "整改监督信息-添加", description = "整改监督信息-添加")
//    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:add")
//    @PostMapping(value = "/add")
//    public Result<String> add(@RequestBody ZyHazardInvestigation zyHazardInvestigation) throws ParseException {
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String departId = loginUser.getDepartIds();
//        String departName = sysDepartService.getDepartNameById(departId);
//        zyHazardInvestigation.setDepartment(departName);
//        zyHazardInvestigationService.save(zyHazardInvestigation);
//        return Result.OK("添加成功！");
//    }


    /**
     * 批量添加
     *
     * @param zyHazardInvestigation
     * @return
     */
    @AutoLog(value = "整改监督信息-批量添加")
    @Operation(summary = "整改监督信息-批量添加", description = "整改监督信息-批量添加")
    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:add")
    @PostMapping(value = "/addBatch")
    public Result<String> addBatch(@RequestBody List<ZyHazardInvestigation> zyHazardInvestigation)  {
        zyHazardInvestigationService.saveBatch(zyHazardInvestigation);
        return Result.OK("添加成功！");
    }



    /**
     * 通过instanceid获取到主表数据的id
     *
     * @return
     */
    public String getEntityId(String id) {
        LambdaQueryWrapper<ZyHazardInvestigation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZyHazardInvestigation::getInstanceId, id);
        ZyHazardInvestigation investigation = zyHazardInvestigationService.getOne(wrapper);
        return investigation.getId();

    }

//    /**
//     * 编辑
//     *
//     * @param zyHazardInvestigationPage
//     * @return
//     */
//    @AutoLog(value = "整改监督信息-编辑")
//    @Operation(summary = "整改监督信息-编辑", description = "整改监督信息-编辑")
//    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:edit")
//    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
//    public Result<String> edit(@RequestBody ZyHazardInvestigationPage zyHazardInvestigationPage) {
//        ZyHazardInvestigation zyHazardInvestigation = new ZyHazardInvestigation();
//        BeanUtils.copyProperties(zyHazardInvestigationPage, zyHazardInvestigation);
//        String id = getEntityId(zyHazardInvestigationPage.getId()).toString();
//        zyHazardInvestigation.setId(id);
//        System.out.println("zyHazardInvestigation = " + zyHazardInvestigation);
//        ZyHazardInvestigation zyHazardInvestigationEntity = zyHazardInvestigationService.getById(zyHazardInvestigation.getId());
//        if (zyHazardInvestigationEntity == null) {
//            return Result.error("未找到对应数据");
//        }
//        zyHazardInvestigationService.updateMain(zyHazardInvestigation, zyHazardInvestigationPage.getZyRectificationInformationList(), zyHazardInvestigationPage.getZyReviewInformationList());
//        return Result.OK("编辑成功!");
//    }

    /**
     * 编辑
     *
     * @param zyHazardInvestigation
     * @return
     */
    @AutoLog(value = "整改监督信息-编辑")
    @Operation(summary = "整改监督信息-编辑", description = "整改监督信息-编辑")
    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ZyHazardInvestigation zyHazardInvestigation) {
        zyHazardInvestigationService.updateById(zyHazardInvestigation);
        return Result.OK("编辑成功!");
    }

//    /**
//     * 通过id删除
//     *
//     * @param id
//     * @return
//     */
//    @AutoLog(value = "整改监督信息-通过id删除")
//    @Operation(summary = "整改监督信息-通过id删除", description = "整改监督信息-通过id删除")
//   //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:delete")
//    @DeleteMapping(value = "/delete")
//    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
//        zyHazardInvestigationService.delMain(id);
//        return Result.OK("删除成功!");
//    }
    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "整改监督信息-通过id删除")
    @Operation(summary = "整改监督信息-通过id删除", description = "整改监督信息-通过id删除")
    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        zyHazardInvestigationService.removeById(id);
        return Result.OK("删除成功!");
    }
//
//    /**
//     * 批量删除
//     *
//     * @param ids
//     * @return
//     */
//    @AutoLog(value = "整改监督信息-批量删除")
//    @Operation(summary = "整改监督信息-批量删除", description = "整改监督信息-批量删除")
//    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:deleteBatch")
//    @DeleteMapping(value = "/deleteBatch")
//    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
//        this.zyHazardInvestigationService.delBatchMain(Arrays.asList(ids.split(",")));
//        return Result.OK("批量删除成功！");
//    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "整改监督信息-批量删除")
    @Operation(summary = "整改监督信息-批量删除", description = "整改监督信息-批量删除")
    //@RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.zyHazardInvestigationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "整改监督信息-通过id查询")
    @Operation(summary = "整改监督信息-通过id查询", description = "整改监督信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ZyHazardInvestigation> queryById(@RequestParam(name = "id", required = true) String id) {
        ZyHazardInvestigation zyHazardInvestigation = zyHazardInvestigationService.getById(id);
        if (zyHazardInvestigation == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(zyHazardInvestigation);

    }


    /**
     * 获取不同安全问题类型
     *
     * @return
     */
    @Operation(summary = "质量检查信息-查询安全类型", description = "中阳质量检查基本信息-查询安全类型")
    @GetMapping(value = "/selectSecurityTypes")
    public Result<Map> selectSecurityTypes() {
        List<DictModel> dictItemsByCode = sysDictService.queryDictItemsByCode("security_type");
        //将list转为map，方便根据键名获取对应的值
        Map<String,String> dictItemsByCodeMap = dictItemsByCode.stream().collect(Collectors.toMap(DictModel::getValue, DictModel::getText));
        return  Result.OK(dictItemsByCodeMap);
    }



    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "中阳整改信息通过主表ID查询")
    @Operation(summary = "整改信息主表ID查询", description = "整改信息-通主表ID查询")
    @GetMapping(value = "/queryZyRectificationInformationByMainId")
    public Result<List<ZyRectificationInformation>> queryZyRectificationInformationListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ZyRectificationInformation> zyRectificationInformationList = zyRectificationInformationService.selectByMainId(id);
        return Result.OK(zyRectificationInformationList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "中阳复查信息通过主表ID查询")
    @Operation(summary = "复查信息主表ID查询", description = "复查信息-通主表ID查询")
    @GetMapping(value = "/queryZyReviewInformationByMainId")
    public Result<List<ZyReviewInformation>> queryZyReviewInformationListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ZyReviewInformation> zyReviewInformationList = zyReviewInformationService.selectByMainId(id);
        return Result.OK(zyReviewInformationList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param zyHazardInvestigation
     */
    @RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZyHazardInvestigation zyHazardInvestigation) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ZyHazardInvestigation> queryWrapper = QueryGenerator.initQueryWrapper(zyHazardInvestigation, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<ZyHazardInvestigation> zyHazardInvestigationList = zyHazardInvestigationService.list(queryWrapper);

        // Step.3 组装pageList
        List<ZyHazardInvestigationPage> pageList = new ArrayList<ZyHazardInvestigationPage>();
        for (ZyHazardInvestigation main : zyHazardInvestigationList) {
            ZyHazardInvestigationPage vo = new ZyHazardInvestigationPage();
            BeanUtils.copyProperties(main, vo);
            List<ZyRectificationInformation> zyRectificationInformationList = zyRectificationInformationService.selectByMainId(main.getId());
            vo.setZyRectificationInformationList(zyRectificationInformationList);
            List<ZyReviewInformation> zyReviewInformationList = zyReviewInformationService.selectByMainId(main.getId());
            vo.setZyReviewInformationList(zyReviewInformationList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "中阳整改监督信息列表");
        mv.addObject(NormalExcelConstants.CLASS, ZyHazardInvestigationPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("中阳整改监督信息数据", "导出人:" + sysUser.getRealname(), "整改监督信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("zyhazardinvestigation:zy_hazard_investigation:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ZyHazardInvestigationPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZyHazardInvestigationPage.class, params);
                for (ZyHazardInvestigationPage page : list) {
                    ZyHazardInvestigation po = new ZyHazardInvestigation();
                    BeanUtils.copyProperties(page, po);
                    zyHazardInvestigationService.saveMain(po, page.getZyRectificationInformationList(), page.getZyReviewInformationList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 获取隐患每天的流程状态
     *
     * @return
     */
    @AutoLog(value = "获取隐患每天的流程状态")
    @Operation(summary = "获取隐患每天的流程状态", description = "获取隐患每天的流程状态")
    @GetMapping(value = "/getDailyCorrectionStatusCount")
    public Result<List<ZyHazardInvestigationFinishStatusVo>> getDailyCorrectionStatusCount(@RequestParam(name = "startDate", required = false) String startDateStr,
                                                                                           @RequestParam(name = "endDate", required = false) String endDateStr,
                                                                                           @RequestParam("siteId") String siteId) throws ParseException {
        List<ZyHazardInvestigationFinishStatusVo> arrayList = new ArrayList<>();
        List<ZyHazardInvestigationFinishStatusVo> mergedList = new ArrayList<>();
        // 创建DateTimeFormatter对象，匹配日期字符串的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (StringUtils.isEmpty(endDateStr)) {
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(7);
            // 转string操作
            startDateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            endDateStr = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            //获取合并集合
            getMergeList(startDateStr, endDateStr, siteId, startDate, endDate, arrayList, mergedList);
        } else {
            // 传入时间段
            // 使用DateTimeFormatter将字符串转换为LocalDate
            LocalDate startDate = LocalDate.parse(startDateStr, formatter);
            LocalDate endDate = LocalDate.parse(endDateStr, formatter);
            getMergeList(startDateStr, endDateStr, siteId, startDate, endDate, arrayList, mergedList);
        }
        return Result.OK(mergedList);
    }

    private void getMergeList(String startDateStr, String endDateStr, String siteId, LocalDate startDate, LocalDate endDate, List<ZyHazardInvestigationFinishStatusVo> arrayList, List<ZyHazardInvestigationFinishStatusVo> mergedList) {
        // 创建空list，并将vo的时间导进来
        while (!startDate.isAfter(endDate)) {
            // 创建或更新VO对象并设置日期
            ZyHazardInvestigationFinishStatusVo vo = new ZyHazardInvestigationFinishStatusVo(); // 假设这是您的VO类的构造方法
            vo.setDate(startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); // 设置日期
            vo.setQualifiedCount("0"); // 设置参数
            vo.setPendingCorrectionCount("0"); // 设置参数

            // 将VO对象添加到列表中
            arrayList.add(vo);

            // 移动到下一天
            startDate = startDate.plusDays(1);
        }

        System.out.println("arrayList = " + arrayList);
        // 获取对应的数据库记录
        List<ZyHazardInvestigationFinishStatusVo> finishStatusVoList = zyHazardInvestigationService.getFinishStatusVoList(startDateStr, endDateStr, siteId);
        System.out.println("finishStatusVoList = " + finishStatusVoList);

        // 遍历时间list
        for (ZyHazardInvestigationFinishStatusVo zyHazardInvestigationFinishStatusVo : arrayList) {
            // 查找对应的匹配记录
            ZyHazardInvestigationFinishStatusVo match = finishStatusVoList.stream()
                    .filter(data -> data.getDate().equals(zyHazardInvestigationFinishStatusVo.getDate()))
                    .findFirst()
                    .orElse(null);
            Integer allPendingCorrectionByResult = zyHazardInvestigationMapper.getAllPendingCorrectionByResult(zyHazardInvestigationFinishStatusVo.getDate(), siteId);
            if (match != null) {
                match.setAllPendingCorrectionCount(allPendingCorrectionByResult.toString());
                mergedList.add(match);
            } else {
                zyHazardInvestigationFinishStatusVo.setAllPendingCorrectionCount(allPendingCorrectionByResult.toString());
                mergedList.add(zyHazardInvestigationFinishStatusVo);
            }
            System.out.println(mergedList);
        }
    }

    /**
     * 获取不同安全问题类型
     *
     * @return
     */
    @Operation(summary = "质量检查信息-通过id查询", description = "中阳质量检查基本信息-通过id查询")
    @GetMapping(value = "/selectProblemTypesBySiteId")
    public Result<Map<String, Long>> selectProblemTypesBySiteId(
            @RequestParam(name = "siteId", required = false) String siteId,
            @RequestParam(name = "startTime", required = false) String startTime,
            @RequestParam(name = "endTime", required = false) String endTime
    ) {
        List<DictModel> zyProblemType = sysDictService.queryDictItemsByCode("zy_safe_type");
        Map<String, Long> map = new HashMap<>(); // 初始化 map 为 Map<String, Long>
        zyProblemType.forEach(dictModel -> map.put(dictModel.getText(), 0L)); // 初始化所有安全级别为0
        List<Map<String, Object>> problemTypecount = zyHazardInvestigationMapper.getProblemTypecount(siteId, startTime, endTime);
        Map<String, Long> map2 = problemTypecount.stream()
                .filter(m -> m.get("problemType") != null) // 过滤掉 null 的 map
                .collect(Collectors.toMap(
                        m -> (String) m.get("problemType"), // 提取qualityType作为键
                        m -> ((Number) m.get("count")).longValue(), // 提取 count 的值并转换为 Long
                        Long::sum // 如果键冲突，使用 Long::sum 来合并值
                ));
        map.forEach((key, value) -> map2.merge(key, value, Long::sum));
        return Result.OK(map2);
    }

    @GetMapping(value = "/selectProblemTypesBySiteId1")
    public Result<List<QualityTypeVo>> selectProblemTypesBySiteId1(
            @RequestParam(name = "siteId", required = false) String siteId,
            @RequestParam(name = "startTime", required = false) String startTime,
            @RequestParam(name = "endTime", required = false) String endTime
    ) {
        List<DictModel> zyProblemType = sysDictService.queryDictItemsByCode("zy_safe_type");
        Map<String, Long> resultMap = new HashMap<>();
        for (DictModel dictModel : zyProblemType) {
            resultMap.put(dictModel.getText(), 0L);
        }
        // 从数据库获取特定站点在特定时间范围内的问题类型及数量
        List<QualityTypeVo> problemTypecount = zyHazardInvestigationMapper.getProblemTypecount1(siteId, startTime, endTime);

        // 过滤掉 name 为 null 的记录，并构建 resultMap
        problemTypecount.stream()
                .filter(qualityTypeVo -> qualityTypeVo.getName() != null) // 过滤掉 name 为 null 的记录
                .forEach(qualityTypeVo -> resultMap.merge(qualityTypeVo.getName(), qualityTypeVo.getCount(), Long::sum));
        // 构造最终的 result 列表
        List<QualityTypeVo> result = zyProblemType.stream()
                .map(dictModel -> {
                    QualityTypeVo vo = new QualityTypeVo();
                    vo.setName(dictModel.getText());
                    vo.setCount(resultMap.getOrDefault(dictModel.getText(), 0L));
                    return vo;
                })
                .collect(Collectors.toList());
        return Result.OK(result);
    }


    // 计算天数差值
    public int calcBetweenDate(String start, String end) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = df.parse(start);
            endDate = df.parse(end);
        } catch (Exception e) {
            System.out.println("日期转换出错");
        }
        int count = (int) ((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
        return count;
    }

    @AutoLog(value = "获取隐患每周的流程状态")
    @Operation(summary = "获取隐患每周的流程状态", description = "获取隐患每周的流程状态")
    @GetMapping(value = "/getWeeklyCorrectionStatusCount")
    public Result<List<ZyHazardInvestigationFinishStatusVo>> getWeeklyCorrectionStatusCount(@RequestParam("siteId") String siteId) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusWeeks(4).with(DayOfWeek.MONDAY);
        LocalDate endOfWeek = endDate.minusWeeks(1).with(DayOfWeek.SUNDAY);

        // 初始化四周的数据
        List<ZyHazardInvestigationFinishStatusVo> initializedList = initializeWeeklyData(startDate, endOfWeek);

        // 查询数据库
        String startDateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String endDateStr = endOfWeek.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println("startDateStr = " + startDateStr);
        System.out.println("endDateStr = " + endDateStr);
        List<ZyHazardInvestigationFinishStatusVo> dbResult = zyHazardInvestigationService.getWeeklyFinishStatusVoList(startDateStr, endDateStr, siteId);
        System.out.println("dbResult = " + dbResult);
        System.out.println("initializedList = " + initializedList);
        // 合并数据
        mergeWeeklyData(initializedList, dbResult);

        return Result.OK(initializedList);
    }


    private List<ZyHazardInvestigationFinishStatusVo> initializeWeeklyData(LocalDate startDate, LocalDate endDate) {
        List<ZyHazardInvestigationFinishStatusVo> resultList = new ArrayList<>();
        while (!startDate.isAfter(endDate)) {
            LocalDate endOfWeek = startDate.plusDays(6).with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
//			String dateRange = getWeekNumber(startDate) + " 至 " + getWeekNumber(endOfWeek);
            String weekNumber = getWeekNumber(startDate);

            ZyHazardInvestigationFinishStatusVo vo = new ZyHazardInvestigationFinishStatusVo();
            vo.setDate(weekNumber); // 设置日期范围
            vo.setPendingCorrectionCount("0"); // 初始化参数
            vo.setQualifiedCount("0"); // 初始化参数

            resultList.add(vo);

            // 移动到下一周
            startDate = endOfWeek.plusDays(1);
        }
        for (int i = 0; i < resultList.size(); i++) {
            System.out.println("resultList.get(i) = " + resultList.get(i));
        }
        return resultList;
    }

    private void mergeWeeklyData(List<ZyHazardInvestigationFinishStatusVo> initializedList, List<ZyHazardInvestigationFinishStatusVo> dbResult) {
        for (ZyHazardInvestigationFinishStatusVo dbVo : dbResult) {
            String weekNumber = dbVo.getDate();
            ZyHazardInvestigationFinishStatusVo match = initializedList.stream()
                    .filter(data -> data.getDate().equals(weekNumber))
                    .findFirst()
                    .orElse(null);
            if (match != null) {
                match.setAllPendingCorrectionCount(dbVo.getPendingCorrectionCount() + match.getAllPendingCorrectionCount());
                match.setPendingCorrectionCount(dbVo.getPendingCorrectionCount());
                match.setQualifiedCount(dbVo.getQualifiedCount());
            }
        }
    }


    private void getWeeklyMergeList(String startDateStr, String endDateStr, String siteId, LocalDate startDate, LocalDate endDate, List<ZyHazardInvestigationFinishStatusVo> arrayList, List<ZyHazardInvestigationFinishStatusVo> mergedList) {
        // 创建空list，并将vo的时间导进来
        while (!startDate.isAfter(endDate)) {
            // 创建或更新VO对象并设置日期
            LocalDate endOfWeek = startDate.plusDays(6);
            String dateRange = getWeekNumber(startDate);
            ZyHazardInvestigationFinishStatusVo vo = new ZyHazardInvestigationFinishStatusVo(); // 假设这是您的VO类的构造方法
            vo.setDate(dateRange); // 设置日期范围
            vo.setQualifiedCount("0"); // 设置参数
            vo.setPendingCorrectionCount("0"); // 设置参数
            // 将VO对象添加到列表中
            arrayList.add(vo);

            // 移动到下一周
            startDate = endOfWeek.plusDays(1);
        }
        System.out.println("arrayList = " + arrayList);
        // 获取对应的数据库记录
        List<ZyHazardInvestigationFinishStatusVo> finishStatusVoList = zyHazardInvestigationService.getFinishStatusVoList(startDateStr, endDateStr, siteId);
        System.out.println("finishStatusVoList = " + finishStatusVoList);

        // 遍历时间list
        for (ZyHazardInvestigationFinishStatusVo zyHazardInvestigationFinishStatusVo : arrayList) {
            // 查找对应的匹配记录
            ZyHazardInvestigationFinishStatusVo match = finishStatusVoList.stream()
                    .filter(data -> data.getDate().equals(zyHazardInvestigationFinishStatusVo.getDate()))
                    .findFirst()
                    .orElse(null);
            Integer allPendingCorrectionByResult = zyHazardInvestigationMapper.getAllPendingCorrectionByResult(zyHazardInvestigationFinishStatusVo.getDate(), siteId);
            if (match != null) {
                match.setAllPendingCorrectionCount(allPendingCorrectionByResult.toString());
                mergedList.add(match);
            } else {
                zyHazardInvestigationFinishStatusVo.setAllPendingCorrectionCount(allPendingCorrectionByResult.toString());
                mergedList.add(zyHazardInvestigationFinishStatusVo);
            }
            System.out.println(mergedList);
        }
    }

    private String getWeekNumber(LocalDate date) {
        WeekFields weekFields = WeekFields.of(Locale.getDefault());
        int weekOfYear = date.get(weekFields.weekOfWeekBasedYear());
        int year = date.getYear();
        return year + "-" + weekOfYear;
    }

    @AutoLog(value = "获取隐患近六个月的流程状态")
    @Operation(summary = "获取隐患近六个月的流程状态", description = "获取隐患近六个月的流程状态")
    @GetMapping(value = "/getMonthlyCorrectionStatusCount")
    public Result<List<ZyHazardInvestigationFinishStatusVo>> getMonthlyCorrectionStatusCount(@RequestParam("siteId") String siteId) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusMonths(6).with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDayOfPreviousMonth = endDate.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
        // 初始化六个月的数据
        List<ZyHazardInvestigationFinishStatusVo> initializedList = initializeMonthlyData(startDate, lastDayOfPreviousMonth);

        // 查询数据库
        String startDateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String endDateStr = lastDayOfPreviousMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<ZyHazardInvestigationFinishStatusVo> dbResult = zyHazardInvestigationService.getMonthlyFinishStatusVoList(startDateStr, endDateStr, siteId);

        // 合并数据
        mergeMonthlyData(initializedList, dbResult);

        return Result.OK(initializedList);
    }

    private List<ZyHazardInvestigationFinishStatusVo> initializeMonthlyData(LocalDate startDate, LocalDate endDate) {
        List<ZyHazardInvestigationFinishStatusVo> resultList = new ArrayList<>();
        while (!startDate.isAfter(endDate)) {
            LocalDate endOfMonth = startDate.with(TemporalAdjusters.lastDayOfMonth());
            String monthNumber = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));

            ZyHazardInvestigationFinishStatusVo vo = new ZyHazardInvestigationFinishStatusVo();
            vo.setDate(monthNumber); // 设置月份
            vo.setPendingCorrectionCount("0"); // 初始化参数
            vo.setQualifiedCount("0"); // 初始化参数

            resultList.add(vo);

            // 移动到下一个月
            startDate = endOfMonth.plusDays(1);
        }
        return resultList;
    }

    private void mergeMonthlyData(List<ZyHazardInvestigationFinishStatusVo> initializedList, List<ZyHazardInvestigationFinishStatusVo> dbResult) {

        Map<String, ZyHazardInvestigationFinishStatusVo> dbMap = new HashMap<>();
        for (ZyHazardInvestigationFinishStatusVo dbVo : dbResult) {
            dbMap.put(dbVo.getDate(), dbVo);
            System.out.println("dbVo = " + dbVo);
        }

        for (ZyHazardInvestigationFinishStatusVo vo : initializedList) {
            String monthNumber = vo.getDate();
            if (dbMap.containsKey(monthNumber)) {
                vo.setPendingCorrectionCount(dbMap.get(monthNumber).getPendingCorrectionCount());
                vo.setQualifiedCount(dbMap.get(monthNumber).getQualifiedCount());
            }
        }
    }

    @Operation(summary="整改监督-导出excel合并单元格", description="整改监督-导出excel合并单元格")
    @GetMapping(value = "/exportXlsMergeCells")
    public Result<byte[]> exportXlsMergeCells(HttpServletRequest request, ZyHazardInvestigation zyHazardInvestigation) throws IOException {
        // Step.1 组装查询条件
        QueryWrapper<ZyHazardInvestigation> queryWrapper =new QueryWrapper<>();
        // 过滤选中数据
        String selections = request.getParameter("selections");
        String department = request.getParameter("department");
        String pid=request.getParameter("pid");
        ZyHazardInvestigationFather zyHazardInvestigationFather = zyHazardInvestigationFatherService.getById(pid);
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            System.out.println("selectionList = " + selectionList);
            queryWrapper.in("id",selectionList);
        }  else if (oConvertUtils.isNotEmpty(department)) {
            List<String> departmentList = Arrays.asList(department.split(","));
            queryWrapper.in("company_department",departmentList);
        }
        // Step.2 获取导出数据
        List<ZyHazardInvestigation> exportList = zyHazardInvestigationService.list(queryWrapper);
        // 2. 生成Excel字节数组
        byte[] excelBytes = zyHazardInvestigationService.generateExcelBytes(exportList,zyHazardInvestigationFather);
        return Result.OK(excelBytes);
    }


    @Operation(summary="整改监督-根据pid查询填报率", description="整改监督-根据pid查询填报率")
    @GetMapping(value = "/getFillingRate")
    public Result<Map<String,Object>> getFillingRate(@RequestParam String pid) {
        Map<String,Object> result = new HashMap<>();
        List<SysDepart> departList = sysDepartService.list();
        Long total = 0L;
        Long complete=0L;
        double fillRate=0.0;
        for (int i = 0; i < departList.size(); i++) {
            total=zyHazardInvestigationService.count(new QueryWrapper<ZyHazardInvestigation>().eq("department", departList.get(i).getDepartName()).eq("pid", pid));
            complete=zyHazardInvestigationService.count(new QueryWrapper<ZyHazardInvestigation>().eq("department", departList.get(i).getDepartName()).eq("result", "合格"));
            if (total!=0L){
                fillRate=(double)complete/total;
                fillRate=new BigDecimal(fillRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                result.put(departList.get(i).getDepartName(), fillRate);
            }
        }
        return Result.OK(result);
    }

    @Operation(summary = "整改监督-根据pid查询超期率", description = "整改监督-根据pid查询超期率")
    @GetMapping(value = "/getOverdueRate")
    public Result<Map<String, Object>> getOverdueRate(@RequestParam String pid) {
        Map<String, Object> result = new HashMap<>();
        List<SysDepart> departList = sysDepartService.list();
        Long total = 0L;
        Long complete = 0L;
        double fillRate = 0.0;
        for (int i = 0; i < departList.size(); i++) {
            total = zyHazardInvestigationService.count(new QueryWrapper<ZyHazardInvestigation>().eq("department", departList.get(i).getDepartName()).eq("pid", pid));
            complete = zyHazardInvestigationService.count(new QueryWrapper<ZyHazardInvestigation>().eq("department", departList.get(i).getDepartName()).eq("pid", pid)
                    .in("result", "待整改", "待复查")
                    .lt("rectification_deadline", DateUtils.getDate()));
            if (total != 0L) {
                fillRate = (double) complete / total;
                fillRate = new BigDecimal(fillRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                result.put(departList.get(i).getDepartName(), fillRate);
            }
        }
        return Result.OK(result);
    }


//    @Operation(summary = "整改监督-根据flag（是否以前发现的问题）查询数量",
//            description = "整改监督-根据flag（是否以前发现的问题）查询数量")
//    @GetMapping(value = "/getSumByFlag")
//    public Result<Map<String, ZyHazardInvestigationPage>> getSumByFlag(@RequestParam String pid) {
//        // 获取所有部门
//        List<SysDepart> departList = sysDepartService.list();
//        if (CollectionUtils.isEmpty(departList)) {
//            return Result.OK(Collections.emptyMap());
//        }
//
//        // 提取部门名称列表，用于批量查询
//        List<String> departNames = departList.stream()
//                .map(SysDepart::getDepartName)
//                .collect(Collectors.toList());
//
//        // 构建查询条件，一次查询所有部门的数据
//        LambdaQueryWrapper<ZyHazardInvestigation> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ZyHazardInvestigation::getPid, pid)
//                .eq(ZyHazardInvestigation::getFlag, "是")
//                .in(ZyHazardInvestigation::getDepartment, departNames);
//
//        // 按部门分组统计数量
//        Map<String, Long> departCountMap = zyHazardInvestigationService.list(queryWrapper).stream()
//                .collect(Collectors.groupingBy(
//                        ZyHazardInvestigation::getDepartment,
//                        Collectors.counting()
//                ));
//
//        // 构建结果映射
//        Map<String, ZyHazardInvestigationPage> result = new HashMap<>(departList.size());
//        for (SysDepart depart : departList) {
//            String departName = depart.getDepartName();
//            // 获取该部门的数量
//            long count = departCountMap.getOrDefault(departName, 0L);
//
//            if (count > 0) {
//                // 这里假设只需要设置数量和质量类型，若有其他需求可调整
//                ZyHazardInvestigationPage page = new ZyHazardInvestigationPage();
//                page.setCount((int) count);
//
//                // 如果需要具体的qualityType，可以根据实际业务场景获取
//                // 这里简单取第一个符合条件的作为示例
//                Optional<ZyHazardInvestigation> first = zyHazardInvestigationService.list(
//                        new LambdaQueryWrapper<ZyHazardInvestigation>()
//                                .eq(ZyHazardInvestigation::getPid, pid)
//                                .eq(ZyHazardInvestigation::getFlag, "是")
//                                .eq(ZyHazardInvestigation::getDepartment, departName)
//                ).stream().findFirst();
//
//                first.ifPresent(zy -> page.setQualityType(zy.getQualityType()));
//
//                result.put(departName, page);
//            }
//        }
//
//        return Result.OK(result);
//    }
    @Operation(summary = "整改监督-根据flag（是否以前发现的问题）查询数量", description = "整改监督-根据flag（是否以前发现的问题）查询数量")
    @GetMapping(value = "/getSumByFlag")
    public Result<Map<String, Long>> getSumByFlag(@RequestParam String pid) {
        // 获取所有部门
        Map<String, Long> result = new HashMap<>();
        List<SysDepart> departList = sysDepartService.list();
        if (CollectionUtils.isEmpty(departList)) {
            return Result.OK(Collections.emptyMap());
        }
        departList.forEach(depart -> {
            LambdaQueryWrapper<ZyHazardInvestigation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZyHazardInvestigation::getPid, pid)
                    .eq(ZyHazardInvestigation::getFlag, "是")
                    .eq(ZyHazardInvestigation::getDepartment, depart.getDepartName());
            if (zyHazardInvestigationService.count(queryWrapper) > 0) {
                result.put(depart.getDepartName(), zyHazardInvestigationService.count(queryWrapper));
            }
        });

        return Result.OK(result);
    }

}
